package com.mls.wms.android.widget.inwh;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.http.RequestManager;
import com.google.zxing.client.android.Intents;
import com.mls.wms.android.R;
import com.mls.wms.android.adapter.InventoryQueryAdapter;
import com.mls.wms.android.constant.ScanTypeConstants;
import com.mls.wms.android.constant.ServicePort;
import com.mls.wms.android.extend.AnimDialogFragment;
import com.mls.wms.android.extend.BaseActivity;
import com.mls.wms.android.extend.MultiListView;
import com.mls.wms.android.model.InventoryQueryModel;
import com.mls.wms.android.model.ResponseResult;
import com.mls.wms.android.util.ViewUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 2014-400 on 2015-09-15.
 */
public class InventoryQueryActivity extends BaseActivity {
    private final int LIST_ITEM_COUNT = 3;
    private final int PAGE_INDEX = 0;
    private final int PAGE_SIZE = 100;

    private EditText etLocationNo = null;
    private EditText etCartonNo = null;
    private EditText etItemBarcode = null;
    private EditText etLotNo = null;
    private EditText selectEt = null;

    private TextView tvMore = null;
    private LinearLayout layoutCartonNo = null;
    private LinearLayout layoutItemBarcode = null;
    private LinearLayout layoutLotNo = null;

    private Button btnReset = null;
    private Button btnQuery = null;

    private MultiListView listHeader = null;
    private InventoryQueryAdapter adapter = null;
    private List<InventoryQueryModel> _listAll = null;
    private List<InventoryQueryModel> _listCurrent = null;

    private AnimDialogFragment progressDialog = null;
    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_inventory_query_list);

        //弹出框
        progressDialog = new AnimDialogFragment();
        progressDialog.setResId(R.drawable.anim_progress_dialog);

        this.etLocationNo = (EditText) this.findViewById(R.id.act_inventory_query_list_et_location_no);
        this.etCartonNo = (EditText) this.findViewById(R.id.act_inventory_query_list_et_carton_no);
        this.etItemBarcode = (EditText) this.findViewById(R.id.act_inventory_query_list_et_item_barcode);
        this.etLotNo = (EditText) this.findViewById(R.id.act_inventory_query_list_et_lot_no);

        this.tvMore = (TextView) this.findViewById(R.id.act_inventory_query_list_tv_more);
        this.tvMore.setTypeface(_BaseApplication.getIconFont());

        this.btnReset = (Button) this.findViewById(R.id.act_inventory_query_list_btn_reset);
        this.btnQuery = (Button) this.findViewById(R.id.act_inventory_query_list_btn_query);

        this.layoutCartonNo = (LinearLayout) this.findViewById(R.id.act_inventory_query_list_layout_carton_no);
        this.layoutItemBarcode = (LinearLayout) this.findViewById(R.id.act_inventory_query_list_layout_item_barcode);
        this.layoutLotNo = (LinearLayout) this.findViewById(R.id.act_inventory_query_list_layout_lot_no);
        this.listHeader = (MultiListView) this.findViewById(R.id.act_inventory_query_list_header);

        //ListView事件
        this.listHeader.setOnRefreshListener(new MultiListView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                load();
            }
        });
        this.listHeader.setOnLoadListener(new MultiListView.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        boolean flag = copyData();
                        adapter.notifyDataSetChanged();

                        listHeader.setCanLoadMore(flag);
                        listHeader.onLoadMoreComplete();
                    }
                }, 1 * 1000);
            }
        });

        //文本框事件
        List<EditText> ets = ViewUtils.getDescendants(this, EditText.class, false);
        for (final EditText item : ets) {
            if (item.isEnabled() == true && item.getVisibility() == View.VISIBLE) {
                item.setSelectAllOnFocus(true);//获取焦点全选
                item.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if (true == hasFocus) {
                            selectEt = item;
                        }
                    }
                });
            }
        }
        //点击更多
        tvMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layoutCartonNo.setVisibility(View.VISIBLE);
                layoutItemBarcode.setVisibility(View.VISIBLE);
                layoutLotNo.setVisibility(View.VISIBLE);
                tvMore.setVisibility(View.GONE);
            }
        });
        //点击查询
        this.btnQuery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layoutCartonNo.setVisibility(View.GONE);
                layoutItemBarcode.setVisibility(View.GONE);
                layoutLotNo.setVisibility(View.GONE);
                tvMore.setVisibility(View.VISIBLE);
                load();
            }
        });
        //点击重置
        this.btnReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etLocationNo.setText("");
                etCartonNo.setText("");
                etItemBarcode.setText("");
                etLotNo.setText("");
            }
        });

    }

    private void load() {
        Map<String, String> paras = new HashMap<String, String>();
        paras.put("warehouseId", _BaseApplication.getGlobalSetting().getWarehouseId() + "");
        paras.put("warehouseNo", _BaseApplication.getGlobalSetting().getWarehouseNo());
        paras.put("warehouseName", _BaseApplication.getGlobalSetting().getWarehouseName());
        paras.put("locationNo", this.etLocationNo.getText().toString().trim());
        paras.put("cartonNo", this.etCartonNo.getText().toString().trim());
        paras.put("barcode", this.etItemBarcode.getText().toString().trim());
        paras.put("lotKey", this.etLotNo.getText().toString().trim());
        paras.put("pageIndex", PAGE_INDEX + "");
        paras.put("pageSize", PAGE_SIZE + "");

        progressDialog.show(getFragmentManager(), this.toString());
        get(ServicePort.getUrl(ServicePort.Inventory), paras, new RequestManager.RequestListener() {
            @Override
            public void onRequest() {

            }

            @Override
            public void onSuccess(String s, Map<String, String> stringStringMap, String s2, int i) {
                try {
                    ResponseResult result = new ResponseResult();
                    result = result.parseJson(s);
                    if (result != null && result.getSuc() == true) {
                        if (result.getResult() == null || TextUtils.isEmpty(result.getResult().toString())) {
                            throw new Exception(getResources().getString(R.string.exception_no_data));
                        }

                        InventoryQueryModel model = new InventoryQueryModel();
                        _listCurrent = null;
                        _listAll = model.parseJsons(result.getResult().toString());

                        boolean flag = copyData();
                        listHeader.setCanLoadMore(flag);

                        adapter = new InventoryQueryAdapter(InventoryQueryActivity.this, _listCurrent);
                        listHeader.setAdapter(adapter);

                        progressDialog.dismiss();
                    } else {
                        String message = result == null ? getResources().getString(R.string.title_text_operate_fail) : result.getMessage();
                        progressDialog.dismiss();
                        Toast.makeText(InventoryQueryActivity.this, message, Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    progressDialog.dismiss();
                    Toast.makeText(InventoryQueryActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                } finally {
                    listHeader.onRefreshComplete();
                }
            }

            @Override
            public void onError(String s, String s2, int i) {
                progressDialog.dismiss();
                Toast.makeText(InventoryQueryActivity.this, s, Toast.LENGTH_SHORT).show();
            }
        }, 1);
    }

    /**
     * 复制数据
     *
     * @return false:数据加载完了
     */
    private boolean copyData() {
        if (_listAll != null) {
            if (_listCurrent == null) {
                _listCurrent = new ArrayList<InventoryQueryModel>();
            }

            if (_listAll.size() > LIST_ITEM_COUNT) {
                for (int i = 0; i < LIST_ITEM_COUNT; i++) {
                    _listCurrent.add(_listAll.get(0));
                    _listAll.remove(0);
                }
            } else {
                _listCurrent.addAll(_listAll);
                _listAll.clear();
                return false;
            }
        }

        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (this.selectEt != null) {
            switch (requestCode) {
                case ScanTypeConstants.SCAN_BAR_CODE:
                    if (resultCode == RESULT_OK) {
                        Bundle bundle = data.getExtras();
                        this.selectEt.setText(bundle.getString(Intents.Scan.RESULT, ""));
                        this.selectEt.requestFocus();
                    }
                default:
                    break;
            }
        }
    }

    @Override
    public int getTopNameResId() {
        return R.string.title_text_inventory_query;
    }
}
